package cn.tedu._05mvcboot03.base.interceptors;

import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author Justin Parker
 * @Date 2024/8/14 0014 14:43
 * @Version 1.0
 */
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("拦截器拦截到了请求：{}", request.getRequestURI());
        /*
         * 1.获取HttpSession会话对象
         *  HttpSession session = request.getSession();
         * 2.通过会话对象，获取用户标识【getAttribute("user")】;
         * 3.判断用户标识是否为空；
         *    3.1 如果不为null,登录状态没有问题，放行 reture true;
         *    3.2 如果为null,未登录，
         *      * 跳转到登录页面
                response.sendRedirect("/login.html");
                * 返回false，拦截请求
         */
        HttpSession session = request.getSession();
        UserVO userVo = (UserVO) session.getAttribute("user");
           if (userVo !=null){
               return true;
           }
        response.sendRedirect("/login.html");
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
